/*
 * Fichier : MessageBean.java
 * Version : 1.0.0
 * Auteurs : Alexandre BOURSIER & Nolan POTIER
 * 
 * Description : Classe modélisant le comportement d'un message bean par l'intermédiare d'un Topic
 */
package club.jeux.session;

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.Stateless;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;
import javax.naming.InitialContext;

@Stateless
public class MessageBean implements MessageBeanLocal {

   @Override
    public String receiveMessage() {
        ConnectionFactory connectionFactory;
        Topic topic;
        Connection connection = null;
        Session jmsSession = null;
        MessageConsumer messageConsumer = null;
        TextMessage message = null;

            try{
                InitialContext ic = new InitialContext();
                connectionFactory = (ConnectionFactory)ic.lookup("jms/TopicConnectionFactory");
                topic = (Topic) ic.lookup("jms/Topic");

                connection = connectionFactory.createConnection();
                jmsSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
                messageConsumer = jmsSession.createConsumer(topic);
                connection.start();
            } catch (Exception ex){
                System.out.println("Erreur Message Bean : " + ex.getMessage());
            }
        try {            
            message = (TextMessage) messageConsumer.receive();
            return message.getText();
        } catch (JMSException ex) {
            Logger.getLogger(Serveur.class.getName()).log(Level.SEVERE, null, ex);
        }
        return "erreur";
        
        
            
    }

}
